const express = require("express");
const fs = require("fs");
const app = express();
const { getDb, saveDb } = require("./db.js");

app.use(express.json()); // 配置解析表达请求体: application/json
app.use(express.urlencoded()); // 解析表单请求体： application/x-www-form-urlencoded

app.get("/todos", async (req, res) => {
  try {
    const db = await getDb();
    res.status(200).json(db.todos);
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});

app.get("/todos/:id", async (req, res) => {
  try {
    const db = await getDb();
    const todo = db.todos.find((todo) => todo.id === parseInt(req.params.id));
    if (!todo) {
      return res.status(404).end();
    }
    res.status(200).json(todo);
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});

app.post("/todos", async (req, res) => {
  // 1. 获取客户端请求体参数
  // 2. 数据验证
  // 3. 数据验证通过，把数据存储到db中
  // console.log(req.body);
  try {
    const todo = req.body;
    if (!todo.title) {
      return res.status(422).json({
        error: "The field title is required",
      });
    }

    const db = await getDb();
    const lastTodo = db.todos[db.todos.length - 1];
    todo.id = lastTodo ? lastTodo.id + 1 : 1;
    db.todos.push(todo);
    await saveDb(db);
    res.status(200).json(todo);
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});

app.patch("/todos/:id", async (req, res) => {
  try {
    const todo = req.body;

    const db = await getDb();
    const ret = db.todos.find((todo) => todo.id === parseInt(req.params.id));

    if (!ret) {
      return res.status(404).end();
    }
    Object.assign(ret, todo);
    await saveDb(db);

    res.status(200).json(ret);
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});

app.delete("/todos/:id", async (req, res) => {
  // res.send(`delete /todos/${req.params.id}`);
  try {
    const todoId = parseInt(req.params.id);
    const db = await getDb();
    const index = db.todos.findIndex((todo) => todo.id === todoId);
    if (index === -1) {
      return res.status(404).end();
    }
    db.todos.splice(index, 1);
    await saveDb(db);
    res.status(204).end();
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
});

app.listen(3000, () => {
  console.log("server is running at 3000");
});
